const path = require('path')
const webpack = require('webpack')
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
const CopyWebpackPlugin = require('copy-webpack-plugin')
const isProduction = process.env.NODE_ENV === 'production'
const isDevelopment = !isProduction

module.exports = {
  publicPath: './',
  
  configureWebpack: {
    devServer: {
      liveReload: true,
      hot: false,
      client: {
        overlay: false,
        progress: false,
        logging: 'none', 
        reconnect: 5 
      },
      devMiddleware: {
        writeToDisk: false,
        stats: 'errors-only'
      },
      compress: false,
    },
    
    resolve: {
      alias: {
        '@': path.resolve(__dirname, 'src'),
        assets: path.resolve(__dirname, 'src/assets'),
        components: path.resolve(__dirname, 'src/components')
      },
      extensions: ['.js', '.vue', '.json'],
      modules: [
        path.resolve(__dirname, 'node_modules'),
        'node_modules'
      ],
      symlinks: false
    },
    
    optimization: {
      splitChunks: {
        chunks: 'all',
        maxSize: 244 * 1024,
        minSize: 20 * 1024,
        cacheGroups: {
          vendors: {
            test: /[\\/]node_modules[\\/]/,
            name: 'chunk-vendors',
            priority: 10,
            reuseExistingChunk: true
          },
          common: {
            name: 'chunk-common',
            minChunks: 2,
            priority: 5,
            reuseExistingChunk: true
          }
        }
      },
      runtimeChunk: {
        name: 'runtime'
      }
    },
    
    plugins: [
      new webpack.DefinePlugin({
        'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
      }),
      
      ...(process.env.ANALYZE ? [
        new BundleAnalyzerPlugin({
          analyzerMode: 'static',
          reportFilename: 'report.html',
          openAnalyzer: false,
          defaultSizes: 'parsed',
          statsOptions: {
            excludeModules: true
          }
        })
      ] : [])
    ]
  },

  
  chainWebpack: config => {
    // 更新Vue loader配置（移除cache-loader相关配置）
    config.module
      .rule('vue')
      .use('vue-loader')
      .loader('vue-loader')
      .tap(options => ({
        hotReload: true,
        ...options
      }))
    
    if (isDevelopment) {
      config.devtool('cheap-module-source-map')
    }
  },
  
  productionSourceMap: false,
  
  css: {
    extract: isProduction,
    sourceMap: false,
    loaderOptions: {
      css: {
        importLoaders: 1
      },
      postcss: {
        postcssOptions: {
          plugins: [
            require('autoprefixer')({
              overrideBrowserslist: [
                'last 2 versions',
                '> 1%',
                'not dead'
              ]
            })
          ]
        }
      }
    }
  },
  
  parallel: require('os').cpus().length > 1,
  
  outputDir: 'dist',
  assetsDir: 'static',
  filenameHashing: true
}